package com.example.netty.pipeline;

import com.example.netty.pipeline.serverInBounds.InBoundHandlerA;
import com.example.netty.pipeline.serverInBounds.InBoundHandlerB;
import com.example.netty.pipeline.serverInBounds.InBoundHandlerC;
import com.example.netty.pipeline.serverOutBounds.OutBoundHandlerA;
import com.example.netty.pipeline.serverOutBounds.OutBoundHandlerB;
import com.example.netty.pipeline.serverOutBounds.OutBoundHandlerC;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author liupk
 * @date 2018/10/23
 */
public class NettyServer {
    
    public static void main(String[] args) {
        /**netty引导类*/
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        /**线程组*/
        /**监听线程租，负责接收新连接，可以理解为boss接活，给员工干*/
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        /**数据处理线程组，主要用于处理读取数据，以及业务逻辑的处理*/
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        /**配置引导类相关参数*/
        serverBootstrap
                .group(bossGroup,workerGroup)
                /**指定IO模型，当然也可以使用BIO*/
                .channel(NioServerSocketChannel.class)
                /**添加初始化处理器*/
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        System.out.println("初始化netty服务器成功");
                        /**通过pipeline，添加不同的业务处理器，注意顺序*/
                        /**inBound，处理读数据的逻辑链*/
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new InBoundHandlerA());
                        pipeline.addLast(new InBoundHandlerB());
                        pipeline.addLast(new InBoundHandlerC());
    
                        /** outBound，处理写数据的逻辑链*/
                        pipeline.addLast(new OutBoundHandlerA());
                        pipeline.addLast(new OutBoundHandlerB());
                        pipeline.addLast(new OutBoundHandlerC());
                    }
                });
        /**绑定端口，启动*/
        serverBootstrap.bind(8002);
    }
}